package models

import (
	"github.com/Unknwon/com"
	"github.com/astaxie/beego/orm"
	_ "github.com/go-sql-driver/mysql"
	// _ "github.com/mattn/go-sqlite3"
	"os"
	"path"
	"strconv"
	"time"
)

const (
	// _DB_NAME = "data/beeblog.db"
	// _DB_DR   = "sqlite3"

	_DB_NAME = "root:root@/app?charset=utf8"
	_DB_DR   = "mysql"
)

// 分类
type Category struct {
	Id             int64
	Title          string
	Views          int64     `orm:"index"`
	TopicTime      time.Time `orm:"index"`
	TopicCount     int64
	TopicLastUsrId int64
	Created        time.Time `orm:"index"`
}

// 文章
type Topic struct {
	Id               int64
	Uid              int64
	Title            string
	Content          string `orm:"size(5000)"`
	Attachment       string
	Created          time.Time `orm:"index"`
	Updated          time.Time `orm:"index"`
	Views            int64     `orm:"index"`
	Author           string    //作者
	ReplyTime        time.Time `orm:"index"`
	ReplyCount       int64
	ReplayLastUserId int64
}

// 用户
type User struct {
	Id            int64
	User          string
	Password      string
	RegistTime    time.Time
	LastLoginTime time.Time
}

func RegisterDB() {

	//注册模型
	orm.RegisterModel(new(Category), new(Topic), new(User))

	if _DB_DR == "sqlite3" {
		//判断文件是否存在
		if !com.IsExist(_DB_NAME) {
			os.MkdirAll(path.Dir(_DB_NAME), os.ModePerm)
			os.Create(_DB_NAME)
		}

		//注册驱动
		orm.RegisterDriver(_DB_DR, orm.DRSqlite)
		//注册数据库
		orm.RegisterDataBase("default", _DB_DR, _DB_NAME, 10)

	} else {

		//注册驱动
		orm.RegisterDriver(_DB_DR, orm.DRMySQL)
		//注册默认数据库
		orm.RegisterDataBase("default", _DB_DR, _DB_NAME)

	}

}

//获取全部的分类
func GetAllCategory() ([]*Category, error) {

	o := orm.NewOrm()
	cates := make([]*Category, 0)
	qs := o.QueryTable("category")
	_, err := qs.All(&cates)
	return cates, err

}

//添加分类
func AddCategory(name string) error {
	o := orm.NewOrm()
	cate := &Category{
		Title:     name,
		TopicTime: time.Now(),
		Created:   time.Now(),
	}

	qs := o.QueryTable("category")
	err := qs.Filter("title", name).One(cate)
	if err == nil {
		return err
	}

	_, err1 := o.Insert(cate)
	if err1 != nil {
		return err1
	}

	return nil
}

// 删除
func DelCategory(id string) error {
	cid, err := strconv.ParseInt(id, 10, 64)
	if err != nil {
		return err
	}

	o := orm.NewOrm()
	cate := &Category{Id: cid}
	_, err = o.Delete(cate)
	return err
}

// 用户表
func GetUser(uname string) {

}
